<style lang="scss">
.cus--no-action {
  .z-table__button:first-child {
    display: none;
  }
}
.cus-opt__list {
  .el-table td.el-table__cell div {
    padding-left: 5px;
    padding-right: 5px;
  }
}
</style>

<template>
  <template v-if="inited">
    <template v-if="state.control">
<!--      {{state.control}}-->
<!--      {{state.checked}}-->
      <div class="cus-opt__list a-space-mb-10" :class="{['cus--no-action']: !showAction}">
        <simple-list @select="onSelectList"
                     :actionProps="actionProps"
                     :column="column"
                     :suggest="state.control"
                    :append-actions="appendActions"
                     v-if="state.showTable"
        ></simple-list>
      </div>

      <div class="a-space-mb-10">
        <el-space>
          <el-button @click="addRow">添加一行</el-button>
          <el-button @click="clear">清空</el-button>
          <z-options-manager @select-item="onSelect"></z-options-manager>
        </el-space>
      </div>

    </template>
  </template>
</template>

<script>
import {CustomRenderControlMixin, defineCustomRender} from "@/plugins/form-render/utils/index.js";
import {inject, nextTick, onMounted, toRaw, watch} from "vue";
import ZOptionsManager from "@/plugins/z-frame/components/ZOptionsManager.vue";
import ZCellItem from "@/plugins/z-frame/components/ZCellItem.vue";
import SimpleList from "@/plugins/z-frame/components/SimpleList.vue";

export default {
  name: 'CusOptManager',
  components: {SimpleList, ZCellItem, ZOptionsManager},
  mixins: [
    CustomRenderControlMixin
  ],
  setup(props, ctx) {
    let curFormCon = inject('curFormCon')
    // console.log(curFormCon)
    let obj;
    let JSON5 = ZY.JSON5;
    let { data, methods, listeners, init, widgetConfig2 } = defineCustomRender(props, ctx, {
      handleValueInit(newVal, from) {
        // console.log(from)
        // console.log('CusOptManager', newVal, typeof  newVal)
        if (newVal) {
          try {
            obj = JSON5.parse(newVal)
            state.control = obj
            state.value = obj
          } catch (e) {
            //
          }
        } else {
          state.control = []
          state.value = []
        }
        state.checked = new Map()
        return {}
      }
    })

    let state = data({
      value: [],
      checked: new Map(),
      control: [],
      showTable: true
    })

    let appendActions = [
      {
        label: '删除',
        on: {
          click(scope) {
            // console.log('scope', scope)
            state.showTable = false
            state.control.splice(scope.$index, 1)
            nextTick(() => {
              onChange()
              state.showTable = true
            })
          }
        },
        attrs: {
          type: 'danger',
          size: 'small'
        },
      }
    ]

    function onChange() {
      let clonedValue = JSON5.parse(JSON5.stringify(state.control))
      let str =JSON5.stringify(clonedValue)
      methods.onChange(str)
    }


    function onSelectChange(e) {
      // console.log('onSelectChange', e)
      // state.control.styles = e
      let options = ZY.JSON5.parse(e)
      // console.log(options)
      state.control = options.map(v => {
        return v.data
      })
      //
      setTimeout(() => {
        onChange()
      }, 30)
    }


    function save() {
      onChange()
    }

    function onSelect(option) {
      // console.log('ctx', option)
      onSelectChange(option.value)
    }

    function clear() {
      onSelectChange('[]')
    }


    function addRow() {
      // console.log( state.control )
      // let arr = ZY.JSON5.parse(ZY.JSON5.stringify( state.control ))
      state.control.push({
        label: '',
        value: '',
        UUID: ZY.rid(),
        d: Date.now()
      })
      state.showTable = false
      // state.control = arr
      nextTick(() => {
        onChange()
        // state.control[state.control.length - 1].label = ''
        state.showTable = true
      })
    }

    function onSelectList(e) {
      // console.log('onSelectList', e)
      curFormCon.callPageEvent('cus:com:fire', {
        name: 'select-list',
      }, {
        origin: e,
      })
    }

    onMounted(() => {
      setTimeout(() => {
        // console.log('props', props)
        if (widgetConfig2.mounted) {
          init(props)
        }
      }, 30)
    })


    function createInput(h, props) {
      let scope = props.scope
      let property = scope.column.property
      return h('input', {
        style: {
          width: '70px',
          border: '1px solid var(--el-border-color-base)'
        },
        value: scope.row[property],
        onChange(e) {
          if (state.control[scope.$index]) {
            state.control[scope.$index][property] = e.target.value
          }
          nextTick(() => {
            onChange()
          })
        }
      })
    }

    let column = [
      { label: '标题', prop: 'label', width: '95px',
        render(h, props) {
          return createInput(h, props)
        }
      },
      { label: '值', prop: 'value', width: '95px',
        render(h, props) {
          return createInput(h, props)
        }
      },
      // { label: 'D', prop: 'd' },
    ]

    let showAction = true
    if (widgetConfig2.multi) {
      column.unshift(
          {
            label: '选择',
            width: '50px',
            prop: 'LAY_CHECKED',
            render(h, props) {
              const scope = props.scope
              let com = CustomVueComponent.resolve('ElCheckbox')
              let checked = scope.row['LAY_CHECKED']
              let value = scope.row['value']
              state.checked.set(toRaw(scope.row), checked)
              // console.log('LAY_CHECKED', scope)
              return h(com, {
                checked: checked,
                onChange(e) {
                  state.checked.set(toRaw(scope.row), e)
                  scope.row.LAY_CHECKED = e
                  const checkedE =  [...state.checked]
                      .filter(([k, v]) => v ).map(r => r[0])
                  // console.log(checkedE)
                  // console.log('change', state.control)
                  curFormCon.callPageEvent('cus:com:fire', {
                    name: 'select-checked',
                  }, {
                    origin: {
                      options: checkedE
                    },
                  })
                  onChange()
                }
                // label: checked
              })
            }
          },
      )
      showAction = false
    }

    let actionProps = {
      // width: '0px'
    }

    return {
      state,
      widgetConfig: widgetConfig2,
      onChange,
      methods,
      column,
      actionProps,
      onSelect,
      clear,
      appendActions,
      onSelectList,
      showAction,
      onSelectChange,
      addRow,
      save,
      listeners,
    }
  },
}
</script>

